package com.example.demo.service.imp;

import com.example.demo.entity.AlarmPlatform;
import com.example.demo.entity.Rule;
import com.example.demo.entity.rep.RuleRep;
import com.example.demo.mapper.AlarmPlatformMapper;
import com.example.demo.mapper.RuleMapper;
import com.example.demo.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RuleServiceImp implements RuleService {

    @Autowired
    private RuleMapper ruleMapper;

    @Autowired
    private AlarmPlatformMapper alarmPlatformMapper;

    @Override
    public List<RuleRep> getAll() {
        List<RuleRep> rules = ruleMapper.getAll();
        List<AlarmPlatform> platforms = alarmPlatformMapper.getAll();
        for (RuleRep rule : rules) {
//            查看是否包含报警平台的 uuid
           if(!rule.getAlarmPlatformUuid().isEmpty()){
//               将 uuid 通过逗号分割开
               List<String> uuids = Arrays.asList(rule.getAlarmPlatformUuid().split(","));
               rule.setAlarmPlatformUuids(uuids);
//               从platforms list 中查找到uuids的 list
               rule.setAlarmPlatforms(platforms.stream().filter(platform -> uuids.contains(platform.getUuid())).collect(Collectors.toList()));
           }
        }
        return rules;
    }


    @Override
    public boolean create(Rule rule) {
       rule.init();
       int affectRows = ruleMapper.insert(rule);
        return affectRows>0;
    }


    @Override
    public boolean update(Rule rule) {
        rule.initUpdate();
        int affectRows = ruleMapper.updateById(rule);
        return affectRows>0;
    }

    @Override
    public boolean delete(String uuid) {
        int affectRows = ruleMapper.deleteById(uuid);
        return affectRows>0;
    }


    @Override
    public boolean updateLastUpdateTime(String uuid) {
        int affectRows = ruleMapper.updateLastUpdateTime(uuid, System.currentTimeMillis());
        return affectRows>0;
    }
}
